package demo1.servlet.userMai;

import com.alibaba.fastjson.JSON;
import demo1.pojo.fileList;
import demo1.pojo.users;
import demo1.service.goodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

@WebServlet("/uploadPicture2")
@MultipartConfig
public class uploadPicture2 extends HttpServlet {//上传照片
    private static final String UPLOAD_DIR = "uploads"; // 服务器上的上传目录
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置上传文件存储的路径
        String uploadPath = "D:/images/";

        // 检查该路径是否存在，不存在则创建
        File file = new File(uploadPath);
        if (!file.exists()) {
            boolean mkdirSuccess = file.mkdir();
            if (!mkdirSuccess) {
                throw new RuntimeException("创建目录失败");
            }
        }

        // 解析请求获取文件名和文件流
        Part filePart = request.getPart("file"); // 假设上传字段的name属性是"file"
        String fileName = filePart.getName();
        InputStream fileContent = filePart.getInputStream();

        // 构建最终的文件保存路径
        File savedFile = new File(uploadPath + fileName+".jpg");
        String name = null;
        if (savedFile.exists()) {
            // 文件已存在，决定如何处理
            // 这里我们选择追加内容到现有文件
            name = System.currentTimeMillis() + "_" + fileName + ".jpg";
            savedFile = new File(uploadPath + name);
        }
        // 将输入流中的数据写入文件
        try (FileOutputStream fos = new FileOutputStream(savedFile)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileContent.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        }
        //获取session对象
        HttpSession session = request.getSession();
        Object userObject = session.getAttribute("users");
        users users = (users) userObject;

//        System.out.println(users.getGoodsID());
//        System.out.println(System.currentTimeMillis() + "_" + fileName + ".jpg");
        goodsService goodsService = new goodsService();
        int num = 0;
        try {
            num = goodsService.updateGoodsUrl(users.getGoodsID(), "http://localhost:8887/"+ name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 设置响应状态码为200，表示成功
        //response.setStatus(HttpServletResponse.SC_OK);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
